<template>
  <div class="pdf-image-viewer">
    <div class="viewer-container">
      <!-- 左侧导航按钮 -->
      <button
          class="nav-button nav-button-prev"
          @click="prevPage"
          :disabled="currentPage === 1"
      >
        <ChevronLeft class="nav-icon" />
      </button>
      <!-- 中间内容区域 -->
      <div class="content-area">
        <div class="page-container" ref="pageContainer">
          <div class="page-content">
            <!-- 封面页 -->
            <div v-if="showCover && currentPage === 1" class="cover-page">
              <div class="cover-content">
                <!-- 动态内容项 -->
                <div
                    v-for="item in coverData.contentItems"
                    :key="item.id"
                    :style="{
                  position: 'absolute',
                  left: '50%',
                  transform: 'translateX(-50%)',
                  top: `${item.position.y}px`,
                  fontSize: getFontSize(item.type),
                  fontFamily: coverData.font,
                  textAlign: 'center',
                  width: '80%'
                }"
                >
                  {{ item.text }}
                </div>
                <!-- 申报信息区域 -->
                <div
                    v-if="coverData.declarationInfo && showDeclarationInfo"
                    class="declaration-info"
                    :style="{
                  position: 'absolute',
                  left: '50%',
                  transform: 'translateX(-50%)',
                  top: `${coverData.declarationInfo.position.y}px`,
                  width: '300px' // Adjust width as needed
                }"
                >
                  <div class="declaration-row">
                  <span class="declaration-label">
                    {{ coverData.declarationInfo.labels.person }}：
                  </span>
                    <div class="declaration-input-wrapper">
                    <span class="declaration-value">
                      {{ coverData.declarationInfo.person }}
                    </span>
                    </div>
                  </div>
                  <div class="declaration-row">
                  <span class="declaration-label">
                    {{ coverData.declarationInfo.labels.unit }}：
                  </span>
                    <div class="declaration-input-wrapper">
                    <span class="declaration-value">
                      {{ coverData.declarationInfo.unit }}
                    </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 目录页 -->
            <div v-else-if="showTableOfContents && currentPage === 2" class="toc-page">
              <div class="toc-content">
                <h2 class="toc-title">目录</h2>
                <div class="toc-list">
                  <div
                      v-for="(item, index) in computedTableOfContents"
                      :key="index"
                      class="toc-item"
                      @click="goToPage(item.pageNumber)"
                  >
                    <span class="toc-item-title">{{ item.title }}</span>
                    <span class="toc-dots">{{ '·'.repeat(30) }}</span>
                    <span class="toc-page-number">{{ item.pageNumber }}</span>
                  </div>
                </div>
              </div>
            </div>
            <!-- 图片页面 -->
            <div v-else class="image-page" :style="{ transform: `scale(${scale})` }">
              <img
                  v-if="getCurrentImageUrl()"
                  :src="getCurrentImageUrl()"
                  :alt="`Page ${currentPage}`"
                  class="page-image"
                  @load="handleImageLoad"
                  @error="handleImageError"
              />
              <div v-else class="empty-page">
                <p>页面内容不可用</p>
              </div>
            </div>
          </div>
        </div>
        <!-- 页面控制器 -->
        <div class="page-controls">
          <button class="page-control-button" @click="goToPage(1)" :disabled="currentPage === 1">
            <ChevronsLeft class="control-icon" />
          </button>
          <button class="page-control-button" @click="prevPage" :disabled="currentPage === 1">
            <ChevronLeft class="control-icon" />
          </button>
          <div class="page-input-container">
            <input
                type="number"
                v-model="pageInputValue"
                @keyup.enter="handlePageInputChange"
                min="1"
                :max="actualTotalPages"
                class="page-input"
            />
            <span class="page-total">/ {{ actualTotalPages }}</span>
          </div>
          <button class="page-control-button" @click="nextPage" :disabled="currentPage === actualTotalPages">
            <ChevronRight class="control-icon" />
          </button>
          <button
              class="page-control-button"
              @click="goToPage(actualTotalPages)"
              :disabled="currentPage === actualTotalPages"
          >
            <ChevronsRight class="control-icon" />
          </button>
        </div>
      </div>
      <!-- 右侧导航按钮 -->
      <button
          class="nav-button nav-button-next"
          @click="nextPage"
          :disabled="currentPage === actualTotalPages"
      >
        <ChevronRight class="nav-icon" />
      </button>
    </div>
    <!-- 右侧设置面板 -->
    <div class="settings-panel">
      <!-- 导航部分 -->
      <div class="panel-section">
        <div class="section-header" @click="toggleSection('navigation')">
          <span class="section-title">导航</span>
          <ChevronDown v-if="!isNavigationOpen" class="section-icon" />
          <ChevronUp v-else class="section-icon" />
        </div>
        <div class="section-content" v-show="isNavigationOpen">
          <button class="nav-link-button" @click="goToPage(1)">跳转到封面</button>
          <button class="nav-link-button" @click="goToPage(2)">跳转到目录</button>
          <div v-for="(item, index) in computedTableOfContents" :key="index" class="toc-nav-item">
            <button class="nav-link-button" @click="goToPage(item.pageNumber)">
              {{ item.title }}
            </button>
          </div>
        </div>
      </div>
      <!-- 设置部分 -->
      <div class="panel-section">
        <div class="section-header" @click="toggleSection('settings')">
          <span class="section-title">设置</span>
          <ChevronDown v-if="!isSettingsOpen" class="section-icon" />
          <ChevronUp v-else class="section-icon" />
        </div>
        <div class="section-content" v-show="isSettingsOpen">
          <label class="setting-item">
            <input type="checkbox" v-model="showCover" />
            <span>显示封面</span>
          </label>
          <label class="setting-item">
            <input type="checkbox" v-model="showTableOfContents" />
            <span>显示目录</span>
          </label>
          <label class="setting-item">
            <input type="checkbox" v-model="showDeclarationInfo" />
            <span>显示申报信息</span>
          </label>
          <!-- 缩放控制 -->
          <div class="zoom-controls">
            <button class="zoom-button" @click="zoomOut" :disabled="scale <= 0.5">
              <ZoomOut class="zoom-icon" />
            </button>
            <span class="zoom-value">{{ Math.round(scale * 100) }}%</span>
            <button class="zoom-button" @click="zoomIn" :disabled="scale >= 2">
              <ZoomIn class="zoom-icon" />
            </button>
          </div>
        </div>
      </div>
      <!-- 编辑部分 -->
      <div class="panel-section">
        <div class="section-header" @click="toggleSection('edit')">
          <span class="section-title">编辑</span>
          <ChevronDown v-if="!isEditOpen" class="section-icon" />
          <ChevronUp v-else class="section-icon" />
        </div>
        <div class="section-content" v-show="isEditOpen">
          <button class="edit-button" @click="$emit('editCover')">
            <Edit class="button-icon" />
            编辑封面
          </button>
        </div>
      </div>
      <!-- 底部按钮 -->
      <div class="bottom-buttons">
        <button class="back-button" @click="$emit('goBack')">
          <ArrowLeft class="button-icon" />
          返回上一步
        </button>
        <button class="generate-button" @click="handleGeneratePdf" :disabled="isGenerating">
          <FileDown class="button-icon" />
          {{ isGenerating ? '生成中...' : '生成PDF' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import {
  ChevronLeft,
  ChevronRight,
  ChevronDown,
  ChevronUp,
  ChevronsLeft,
  ChevronsRight,
  ZoomIn,
  ZoomOut,
  Edit,
  ArrowLeft,
  FileDown
} from 'lucide-vue-next'

// Props
const props = defineProps({
  imageUrls: {
    type: Array,
    default: () => []
  },
  totalPages: {
    type: Number,
    default: 0
  },
  coverData: { // Updated prop structure
    type: Object,
    default: () => ({
      contentItems: [],
      font: 'SimHei, 黑体',
      declarationInfo: {
        person: '',
        unit: '',
        position: { y: 400 },
        labels: {
          person: '申报人',
          unit: '申报单位'
        }
      }
    })
  },
  tableOfContents: {
    type: Array,
    default: () => []
  },
  materialPageCounts: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['generatePdf', 'editCover', 'goBack'])

// 响应式数据
const currentPage = ref(1)
const pageInputValue = ref('1')
const scale = ref(1)
const showCover = ref(true)
const showTableOfContents = ref(true)
const showDeclarationInfo = ref(true)
const isGenerating = ref(false)

// 面板展开状态
const isNavigationOpen = ref(true)
const isSettingsOpen = ref(false)
const isEditOpen = ref(false)

// 获取字体大小的辅助函数 (与 CoverEditor 和 pdf-preview-page 保持一致)
const getFontSize = (type) => {
  switch (type) {
    case 'h1': return '32px'
    case 'h2': return '24px'
    case 'h3': return '20px'
    default: return '16px'
  }
}

// 计算实际总页数
const actualTotalPages = computed(() => {
  let total = props.totalPages
  if (showCover.value) total += 1
  if (showTableOfContents.value) total += 1
  return total
})

// 计算目录中每个材料的实际页码
const computedTableOfContents = computed(() => {
  if (!props.tableOfContents || props.tableOfContents.length === 0) {
    return []
  }
  const result = []
  let currentPageNumber = 1
  if (showCover.value) {
    currentPageNumber += 1
  }
  if (showTableOfContents.value) {
    currentPageNumber += 1
  }
  props.tableOfContents.forEach((item, index) => {
    result.push({
      ...item,
      pageNumber: currentPageNumber
    })
    const pageCount = props.materialPageCounts[index] || 1
    currentPageNumber += pageCount
  })
  return result
})

// 获取当前页面的图片URL
const getCurrentImageUrl = () => {
  if (showCover.value && currentPage.value === 1) {
    return null
  }
  if (showTableOfContents.value && currentPage.value === 2) {
    return null
  }
  let imageIndex = currentPage.value - 1
  if (showCover.value) imageIndex -= 1
  if (showTableOfContents.value) imageIndex -= 1
  return props.imageUrls[imageIndex] || null
}

// 翻页方法
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < actualTotalPages.value) {
    currentPage.value++
  }
}

const goToPage = (pageNumber) => {
  if (pageNumber >= 1 && pageNumber <= actualTotalPages.value) {
    currentPage.value = pageNumber
  }
}

// 处理页码输入
const handlePageInputChange = () => {
  const pageNum = parseInt(pageInputValue.value)
  if (!isNaN(pageNum) && pageNum >= 1 && pageNum <= actualTotalPages.value) {
    goToPage(pageNum)
  } else {
    pageInputValue.value = currentPage.value.toString()
  }
}

// 缩放方法
const zoomIn = () => {
  if (scale.value < 2) {
    scale.value += 0.1
  }
}

const zoomOut = () => {
  if (scale.value > 0.5) {
    scale.value -= 0.1
  }
}

// 面板切换
const toggleSection = (section) => {
  switch (section) {
    case 'navigation':
      isNavigationOpen.value = !isNavigationOpen.value
      break
    case 'settings':
      isSettingsOpen.value = !isSettingsOpen.value
      break
    case 'edit':
      isEditOpen.value = !isEditOpen.value
      break
  }
}

// 生成PDF
const handleGeneratePdf = async () => {
  isGenerating.value = true
  try {
    await emit('generatePdf')
  } finally {
    isGenerating.value = false
  }
}

// 图片加载处理
const handleImageLoad = () => {
  console.log('图片加载成功')
}

const handleImageError = () => {
  console.error('图片加载失败')
}

// 监听当前页变化
watch(currentPage, (newVal) => {
  pageInputValue.value = newVal.toString()
})

// 监听显示设置变化，重新计算当前页
watch([showCover, showTableOfContents], () => {
  if (currentPage.value > actualTotalPages.value) {
    currentPage.value = actualTotalPages.value
  }
})

// 监听 coverData prop 的变化，用于调试
watch(() => props.coverData, (newVal, oldVal) => {
  console.log('--- PdfImageViewer: coverData prop 发生变化 ---');
  console.log('新的 coverData:', JSON.parse(JSON.stringify(newVal)));
  console.log('旧的 coverData:', JSON.parse(JSON.stringify(oldVal)));
  console.log('---------------------------------------------');
}, { deep: true });

onMounted(() => {
  pageInputValue.value = currentPage.value.toString()
})
</script>

<style scoped>
.pdf-image-viewer {
  display: flex;
  height: 100vh;
  background-color: #f5f5f5;
}
.viewer-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  padding: 20px;
}
.nav-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
  background-color: rgba(255, 255, 255, 0.9);
  border: none;
  border-radius: 50%;
  width: 48px;
  height: 48px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}
.nav-button:hover {
  background-color: rgba(255, 255, 255, 1);
}
.nav-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.nav-button-prev {
  left: 300px;
}
.nav-button-next {
  right: 300px; /* 为右侧面板留出空间 */
}
.nav-icon {
  width: 24px;
  height: 24px;
  color: #666;
}
.content-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  max-width: 800px;
  width: 100%;
}
.page-container {
  width: 595px; /* A4宽度 */
  height: 842px; /* A4高度 */
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background-color: white;
  border-radius: 4px;
  overflow: hidden;
}
.page-content {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}
/* 封面样式 */
.cover-page {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column; /* Changed to column for content items */
  align-items: center;
  justify-content: flex-start; /* Align items to start for positioning */
  background-color: white;
  position: relative; /* Needed for absolute positioning of content items */
  padding: 40px; /* Add padding to match preview-area */
  box-sizing: border-box;
}
.cover-content {
  /* This div is no longer needed as content items are absolutely positioned */
  /* text-align: center; */
  /* padding: 40px; */
}
/* Dynamic content item styles are handled inline in template */
/* .cover-title, .cover-subtitle are replaced by dynamic content items */
.declaration-info {
  /* Styles for declaration info, adjusted for absolute positioning */
  position: absolute; /* Changed to absolute */
  left: 50%;
  transform: translateX(-50%);
  width: 300px; /* Fixed width as in reference */
  display: flex;
  flex-direction: column;
  gap: 20px; /* Adjusted gap */
  background-color: rgba(255, 255, 255, 0.9);
  padding: 20px; /* Adjusted padding */
  border-radius: 8px;
  border: 2px solid transparent;
  transition: all 0.2s;
}
.declaration-row {
  display: flex;
  align-items: center;
  gap: 5px; /* 减小间距，让冒号更靠近输入区 */
  width: 100%; /* 确保整行宽度一致 */
}
.declaration-label {
  width: 80px; /* 固定标签宽度（关键：确保冒号对齐） */
  text-align: right; /* 文本右对齐，冒号自然靠右 */
  font-size: 18px;
  font-weight: 500;
  white-space: nowrap; /* 防止标签换行 */
  padding-right: 5px; /* 微调冒号与输入区的间距 */
}
.declaration-input-wrapper {
  flex: 1;
  position: relative;
  min-width: 200px;
  text-align: center;
}
.declaration-input-wrapper::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 1px;
  background-color: #333;
}
.declaration-value {
  font-size: 18px;
  padding: 0 5px;
  display: inline-block; /* 确保文本在容器内居中 */
}
/* 目录样式 */
.toc-page {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  background-color: white;
  padding: 40px;
}
.toc-content {
  width: 100%;
}
.toc-title {
  font-size: 28px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 40px;
  color: #333;
}
.toc-list {
  max-width: 500px;
  margin: 0 auto;
}
.toc-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}
.toc-item:hover {
  background-color: #f0f0f0;
}
.toc-item-title {
  flex-shrink: 0;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.toc-dots {
  flex: 1;
  text-align: center;
  color: #ccc;
  margin: 0 10px;
  overflow: hidden;
  white-space: nowrap;
}
.toc-page-number {
  flex-shrink: 0;
  font-weight: 500;
  color: #0066cc;
}
/* 图片页面样式 */
.image-page {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  transform-origin: center;
  transition: transform 0.2s ease;
}
.page-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
.empty-page {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 18px;
}
/* 页面控制器样式 */
.page-controls {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 24px;
  padding: 8px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.page-control-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: background-color 0.2s;
}
.page-control-button:hover {
  background-color: #f0f0f0;
}
.page-control-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.control-icon {
  width: 18px;
  height: 18px;
  color: #666;
}
.page-input-container {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 0 8px;
}
.page-input {
  width: 60px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 14px;
}
.page-total {
  font-size: 14px;
  color: #666;
}
/* 设置面板样式 */
.settings-panel {
  width: 280px;
  background-color: white;
  border-left: 1px solid #e5e5e5;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow-y: auto;
  height: 100vh;
}
.panel-section {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 16px;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  padding: 8px 0;
}
.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}
.section-icon {
  width: 16px;
  height: 16px;
  color: #999;
}
.section-content {
  margin-top: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.nav-link-button {
  background: none;
  border: none;
  text-align: left;
  padding: 8px 0;
  cursor: pointer;
  color: #0066cc;
  font-size: 14px;
  transition: color 0.2s;
}
.nav-link-button:hover {
  color: #0052a3;
}
.toc-nav-item {
  margin-left: 16px;
}
.setting-item {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
}
.setting-item input[type="checkbox"] {
  margin: 0;
}
.zoom-controls {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px;
  border: 1px solid #e5e5e5;
  border-radius: 6px;
  margin-top: 8px;
}
.zoom-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: background-color 0.2s;
}
.zoom-button:hover {
  background-color: #f0f0f0;
}
.zoom-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.zoom-icon {
  width: 16px;
  height: 16px;
  color: #666;
}
.zoom-value {
  font-size: 14px;
  font-weight: 500;
  color: #666;
}
.edit-button {
  width: 100%;
  padding: 8px 12px;
  background-color: white;
  border: 1px solid #00b96b;
  color: #00b96b;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 14px;
}
.edit-button:hover {
  background-color: #00b96b;
  color: white;
}
.bottom-buttons {
  margin-top: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.back-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px 16px;
  background-color: white;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
}
.back-button:hover {
  border-color: #00b96b;
  color: #00b96b;
}
.generate-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px 16px;
  background-color: #00b96b;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
  font-size: 14px;
}
.generate-button:hover {
  background-color: #009b5a;
}
.generate-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
.button-icon {
  width: 16px;
  height: 16px;
}
/* 响应式设计 */
@media (max-width: 1024px) {
  .settings-panel {
    width: 240px;
  }
  .page-container {
    width: 500px;
    height: 707px;
  }
  .nav-button-next {
    right: 260px;
  }
}
@media (max-width: 768px) {
  .pdf-image-viewer {
    flex-direction: column;
  }
  .settings-panel {
    width: 100%;
    height: auto;
    border-left: none;
    border-top: 1px solid #e5e5e5;
    max-height: 300px;
  }
  .page-container {
    width: 90vw;
    height: 60vh;
  }
  .nav-button {
    display: none;
  }
  .nav-button-next {
    right: 20px;
  }
}
</style>
